// assessment.js：封装“测评管理”的前端请求方法，供页面调用
import request from '@/utils/request'

// 获取测评列表
export function getAssessmentList(params) {
  const page = params?.page ?? params?.pageNum ?? params?.current ?? 1
  const pageSize = params?.pageSize ?? params?.size ?? 10
  const rawCategory = params?.category_id ?? params?.categoryId ?? ''
  const rawKeyword = params?.keyWords ?? params?.keyword ?? ''

  const category = (typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory) || ''
  const keyword = (typeof rawKeyword === 'string' ? rawKeyword.trim() : rawKeyword) || ''

  const payload = {
    page: Math.max(1, parseInt(page) || 1),
    pageSize: Math.max(1, parseInt(pageSize) || 10)
  }

  // 同时兼容两种命名，按后端可识别的为准
  if (category !== '') {
    payload.category_id = category
    payload.categoryId = category
  }
  if (keyword !== '') {
    payload.keyWords = keyword
    payload.keyword = keyword
  }

  console.log('发送到后端的参数:', payload)

  return request.post('/management/assessment/assessments', payload)
}

// 添加测评
export function addAssessment(data) {
  // 如果是FormData，直接发送
  if (data instanceof FormData) {
    return request.post('/management/assessment/addAssessment', data)
  }

  // 如果是普通对象，转换为FormData
  const formData = new FormData()
  Object.keys(data).forEach(key => {
    if (data[key] !== null && data[key] !== undefined) {
      formData.append(key, data[key])
    }
  })
  return request.post('/management/assessment/addAssessment', formData)
}

// 修改测评状态
export function updateAssessmentStatus(params) {
  const assessmentId = params?.assessment_id ?? params?.assessmentId ?? ''
  const status = params?.status ?? ''
  const payload = {
    assessment_id: assessmentId,
    assessmentId: assessmentId,
    status: status
  }
  Object.keys(payload).forEach(k => {
    if (payload[k] === '' || payload[k] === null || payload[k] === undefined) {
      delete payload[k]
    }
  })
  return request.get('/management/assessment/status', { params: payload })
}

// 修改测评基本信息
export function updateAssessment(data) {
  // 如果是FormData，直接发送
  if (data instanceof FormData) {
    console.log('updateAssessment - 直接使用FormData:')
    for (const [key, value] of data.entries()) {
      console.log(`${key}:`, value)
    }
    return request.put('/management/assessment/update', data)
  }

  // 如果是普通对象，转换为FormData
  const formData = new FormData()

  // 确保所有必需字段都存在
  formData.append('assessment_id', data.assessment_id || '')
  formData.append('name', data.name || '')
  formData.append('category_id', data.category_id || '')
  formData.append('introduction', data.introduction || '')
  formData.append('coverImg', '') // 后端期望MultipartFile，即使为空也要传递

  console.log('updateAssessment - 转换后的FormData:')
  for (const [key, value] of formData.entries()) {
    console.log(`${key}:`, value)
  }

  return request.put('/management/assessment/update', formData)
}

// 获取测评题目列表
export function getAssessmentQuestions(params) {
  const assessmentId = params?.assessment_id ?? params?.assessmentId ?? ''
  const queryParams = {
    assessment_id: assessmentId,
    assessmentId: assessmentId
  }
  Object.keys(queryParams).forEach(k => {
    if (queryParams[k] === '' || queryParams[k] === null || queryParams[k] === undefined) {
      delete queryParams[k]
    }
  })
  return request.get('/management/assessment/questions', { params: queryParams })
}

// 添加题目
export function addQuestions(data) {
  console.log('addQuestions - 输入数据:', data)

  // 处理数据，确保格式正确
  if (Array.isArray(data)) {
    const processedData = data.map(item => {
      const processedItem = { ...item }

      // 确保选项字段是数组格式
      if (Array.isArray(item.options)) {
        processedItem.options = item.options
      } else if (typeof item.options === 'string') {
        try {
          processedItem.options = JSON.parse(item.options)
        } catch (e) {
          processedItem.options = []
        }
      }

      // 适配后端字段：统一使用 camelCase 的 sortOrder
      if (processedItem.sort_order !== undefined && processedItem.sort_order !== null) {
        processedItem.sortOrder = processedItem.sort_order
        delete processedItem.sort_order
      } else if (processedItem.sortOrder === undefined) {
        processedItem.sortOrder = 0
      }

      console.log('处理后的题目项:', processedItem)
      return processedItem
    })

    console.log('最终发送的数据:', processedData)
    return request.post('/management/assessment/addQuestions', processedData)
  }

  console.log('非数组数据，直接发送:', data)
  return request.post('/management/assessment/addQuestions', data)
}

// 删除题目
export function deleteQuestions(data) {
  // 后端要求：Body 为整数数组，例如 [1] 或 [1,2,3]
  const ids = Array.isArray(data)
    ? data
    : [data?.questionId ?? data?.id ?? data].filter(v => v !== undefined && v !== null)

  return request.delete('/management/assessment/question', ids)
}

// 修改题目
export function updateQuestion(data) {
  // 兼容不同后端字段命名与格式
  const isArray = Array.isArray(data.options)
  const optionsArray = isArray
    ? data.options
    : (typeof data.options === 'string' ? (() => { try { return JSON.parse(data.options) } catch { return [] } })() : [])

  const payload = {
    // 题目ID
    question_id: data.question_id,
    questionId: data.question_id,
    // 关联测评（可选，但传上更稳妥）
    assessment_id: data.assessment_id,
    assessmentId: data.assessment_id,
    // 基本信息
    topic: data.topic,
    question_type: data.question_type,
    questionType: data.question_type,
    // 选项（同时传数组与字符串，兼容不同后端）
    options: optionsArray,
    optionsStr: JSON.stringify(optionsArray),
    // 排序（双写）
    sortOrder: data.sort_order ?? data.sortOrder ?? 0,
    sort_order: data.sort_order ?? data.sortOrder ?? 0
  }

  // 清理空值
  Object.keys(payload).forEach(k => {
    if (payload[k] === '' || payload[k] === null || payload[k] === undefined) {
      delete payload[k]
    }
  })

  return request.put('/management/assessment/question', payload)
}

// 分类映射
export const categoryMap = {
  'jiuye': '就业',
  'study': '学习',
  'emotion': '情感'
}

// 状态映射
export const statusMap = {
  1: '启用',
  2: '禁用'
}

// 测试函数：尝试不同的更新方式
export function testUpdateAssessment(data) {
  console.log('=== 测试更新测评 ===')
  console.log('输入数据:', data)

  // 方式1：使用FormData，包含空文件
  const formData1 = new FormData()
  formData1.append('assessment_id', data.assessment_id || '')
  formData1.append('name', data.name || '')
  formData1.append('category_id', data.category_id || '')
  formData1.append('introduction', data.introduction || '')

  // 创建一个空的Blob作为coverImg
  const emptyBlob = new Blob([''], { type: 'application/octet-stream' })
  formData1.append('coverImg', emptyBlob, 'empty.txt')

  console.log('方式1 - FormData with empty file:')
  for (const [key, value] of formData1.entries()) {
    console.log(`${key}:`, value)
  }

  return request.put('/management/assessment/update', formData1)
}
